<template>
  <div class="app-container workTripSummary">
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" :inline="true">
      <el-form-item label="出差人员" prop="outers" class="treeselect-form">
        <treeselect
          v-model="queryParams.outers"
          :options="userOptions"
          :disable-branch-nodes="true"
          :clearable="true"
          value-format="object"
          placeholder="请选择出差人员"
          style="width: 240px"
        />
      </el-form-item>

      <el-form-item label="出差地址" prop="outPlace">
        <el-input
          v-model="queryParams.outPlace"
          placeholder="请输入出差地址"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="日期">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['plan:planList:add']"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          v-hasPermi="['plan:planList:remove']"
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          v-hasPermi="['plan:planList:export']"
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" border :data="planList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" fixed="left" />

      <el-table-column label="出差计划" prop="outPlan" align="center" show-overflow-tooltip min-width="200">
        <template slot-scope="scope">
          <span class="planName" @click="handleUpdate(scope.row, false)">{{ scope.row.outPlan }}</span>
        </template>
      </el-table-column>

      <el-table-column label="出差总结" prop="outContent" align="center" show-overflow-tooltip min-width="200" />

      <el-table-column label="出差地址" prop="outPlace" min-width="150" align="center" show-overflow-tooltip />

      <el-table-column label="出差人" prop="outers" min-width="180" align="center" show-overflow-tooltip />

      <el-table-column label="关联任务" prop="dispath" align="center" show-overflow-tooltip min-width="160" />

      <el-table-column label="开始时间" prop="outStarttime" min-width="180" align="center" show-overflow-tooltip />

      <el-table-column label="结束时间" prop="outEndtime" min-width="180" align="center" show-overflow-tooltip />

      <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
        <template v-if="scope.row.roleId !== 1" slot-scope="scope">
          <el-button
            v-hasPermi="['plan:planList:edit']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row, true)"
          >修改</el-button>
          <el-button
            v-hasPermi="['plan:planList:remove']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :before-close="cancel" :visible.sync="open" :close-on-click-modal="false" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="出差计划" prop="outPlan">
              <el-input v-model="form.outPlan" :disabled="!canEdit" type="textarea" :rows="5" placeholder="请输入出差计划" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="出差总结" prop="outContent">
              <el-input v-model="form.outContent" :disabled="!canEdit" type="textarea" :rows="5" placeholder="请输入出差总结" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="出差地址" prop="outPlace">
              <el-input v-model="form.outPlace" :disabled="!canEdit" type="input" placeholder="请输入出差地址" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="出差人员" prop="outerId">
              <treeselect
                v-model="form.outerId"
                :disabled="!canEdit"
                :options="userOptions"
                value-consists-of="LEAF_PRIORITY"
                :multiple="true"
                :clearable="true"
                placeholder="请选择出差人员"
                @input="outerChanges"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="出差日期" prop="addDateRange">
              <el-date-picker
                v-model="addDateRange"
                :disabled="!canEdit"
                value-format="yyyy-MM-dd"
                type="daterange"
                :picker-options="pickerOptions"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                align="right"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="关联任务" prop="dispath">
              <el-tooltip slot="label" class="item" effect="dark" content="选择出差总结关联的任务" placement="top">
                <i class="el-icon-info">关联任务</i>
              </el-tooltip>

              <el-select
                v-model="form.dispath"
                :disabled="!canEdit"
                multiple
                clearable
                filterable
                remote
                reserve-keyword
                placeholder="请选择关联任务"
                :remote-method="projectRemoteMethod"
                :loading="taskLoading"
              >
                <el-option
                  v-for="item in taskOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="描述" prop="contents">
              <editor v-model="form.contents" upload-url="/oa/file/uploadSingleFile" :min-height="192" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :disabled="!canEdit" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOut, userDeptTree, getOutDetail, deleteOut, addOut, updateOut } from '@/api/plan/workTripSummary'
import { listTask } from '@/api/work/task'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  name: 'WorkTripSummary',

  components: { Treeselect },

  data() {
    var validateAddDateRange = (rule, value, callback) => {
      if (!this.addDateRange || this.addDateRange.length <= 0) {
        callback(new Error('请请选择出差日期'))
      } else {
        callback()
      }
    }

    return {
      // 遮罩层
      loading: true,
      // 选择关联任务
      taskLoading: false,
      // 关联任务列表
      taskOptions: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      planList: [],
      // 用户树形数据
      userOptions: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 能否编辑
      canEdit: true,
      // 查询日期范围
      dateRange: null,
      // 新增修改日期范围
      addDateRange: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      // 表单参数
      form: {},
      pickerOptions: {
        shortcuts: [{
          text: '最近3天',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 3)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      // 表单校验
      rules: {
        outPlan: [
          { required: true, message: '请填写出差计划', trigger: 'blur' }
        ],
        outContent: [
          { required: true, message: '请填写出差总结', trigger: 'blur' }
        ],
        outPlace: [
          { required: true, message: '请填写出差地址', trigger: 'blur' }
        ],
        addDateRange: [
          { required: true, validator: validateAddDateRange, trigger: 'change' }
        ],
        outerId: [
          { required: true, message: '请选择出差人员', trigger: 'change' }
        ]
      }
    }
  },

  created() {
    this.getList()
    this.userDeptTree()
  },

  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true
      const params = {
        ...this.queryParams,
        outers: this.queryParams.outers && this.queryParams.outers.label,
        outStarttime: this.dateRange && this.dateRange[0],
        outEndtime: this.dateRange && this.dateRange[1]
      }
      console.log('查询列表参数', params)
      listOut(params).then(response => {
        this.planList = response.rows
        this.total = response.total
        this.loading = false
      })
    },

    /** 查询部门人员下拉树结构 */
    userDeptTree() {
      userDeptTree().then(response => {
        this.userOptions = this.diGuiTreeEdit(response.data)
      })
    },

    // 禁用最后一级非人员节点
    diGuiTreeEdit(item) {
      const data = item
      const treeAry = []
      for (const i in data) {
        const val = data[i]
        const node = {}
        if (val) {
          if (val.children && val.children.length > 0) {
            node.id = val.id
            node.label = val.label
            node.children = this.diGuiTreeEdit(val.children)
            treeAry.push(node)
          } else {
            if (val.type === '0') {
              node.isDisabled = true
            } else {
              node.isDisabled = false
            }
            node.id = val.id
            node.label = val.label
            treeAry.push(node)
          }
        }
      }
      return treeAry
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },

    // 表单重置
    reset() {
      this.form = {
        outPlan: undefined,
        outContent: undefined,
        outPlace: undefined,
        outerId: undefined,
        outStarttime: undefined,
        outEndtime: undefined,
        dispath: undefined,
        contents: undefined
      }
      this.addDateRange = null
      this.resetForm('form')
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = null
      this.resetForm('queryForm')
      this.handleQuery()
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection // .map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.canEdit = true
      this.title = '新增出差总结'
    },

    /** 修改按钮操作 */
    handleUpdate(row, canEdit) {
      this.reset()
      getOutDetail(row.id).then(response => {
        this.form = {
          id: response.data.id,
          outPlan: response.data.outPlan,
          outContent: response.data.outContent,
          outPlace: response.data.outPlace,
          contents: response.data.contents,
          outerId: response.data.outerId.split(',').map(Number),
          dispath: response.data.dispath && response.data.dispath.split(',')
        }
        this.addDateRange = [response.data.outStarttime, response.data.outEndtime]
        this.open = true
        this.canEdit = !!canEdit
        this.title = canEdit ? '修改出差总结' : '详情'
      })
    },

    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.title === '修改出差总结') {
            const params = {
              ...this.form,
              outStarttime: this.addDateRange && this.addDateRange[0],
              outEndtime: this.addDateRange && this.addDateRange[1],
              outerId: this.form.outerId.join(','),
              dispath: this.form.dispath.join(',')
            }
            console.log('修改params', params)
            updateOut(params).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            const params = {
              ...this.form,
              outStarttime: this.addDateRange && this.addDateRange[0],
              outEndtime: this.addDateRange && this.addDateRange[1],
              outerId: this.form.outerId.join(','),
              dispath: this.form.dispath.join(',')
            }
            console.log('新增params', params)
            addOut(params).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const roleIds = row.id || this.ids.map(item => item.id)
      const msg = row.outStarttime || this.ids.map(item => item.outStarttime)
      this.$modal.confirm('是否确认开始日期为"' + msg + '"的出差计划？').then(function() {
        return deleteOut(roleIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },

    // 新增、修改出差人员变动监听
    outerChanges() {
      this.$refs['form'].validateField('outerId')
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('oa/out/export', {
        ...this.queryParams
      }, `出差总结_${new Date().getTime()}.xlsx`, 'get', 'local')
    },

    // 远程搜索关联任务
    projectRemoteMethod(query) {
      if (query) {
        this.taskLoading = true
        listTask({ title: query }).then(res => {
          this.taskOptions = res.rows.map(val => {
            return {
              label: val.title,
              value: val.title
            }
          })
          this.taskLoading = false
        })
      } else {
        this.taskOptions = []
      }
    }
  }
}
</script>

<style lang="scss">
.workTripSummary{
  .planName{
    color: #1890ff;
    cursor: pointer;

    &:hover{
      color: #1682e6;
    }
  }

  .tableRemarks {
    max-width: 100px;
    max-height: 100px;

    ::v-deep p {
      margin: 0;
    }
  }
}
</style>
